var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

const bodyParser = require('body-parser')
const expressJwt = require('express-jwt')
var session = require('express-session');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var systemRouter = require('./routes/system');
var cors = require('cors');
var app = express();


// 解析 post body
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(bodyParser.json());
//  开启 CORS 跨域 
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');

  if (req.method == 'OPTIONS') {
    res.send(200);
    /让options请求快速返回/
  } else {
    next();
  }
});
app.use(cors({
  'Access-Control-Allow-Headers': 'Content-Type, Authorization'
}));
app.use(expressJwt({
  secret: 'Fizz', // 签名的密钥 或 PublicKey 
  algorithms: ['HS256'],
  credentialsRequired: false,
  getToken: function (req) {
    if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
      return req.headers.authorization.split(' ')[1];
    } else if (req.query && req.query.token) {
      return req.query.token;
    }
    return null;
  }
}).unless({
  path: ['/api/login', ''] // 指定路径不经过 Token 解析
}))

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
  extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/api', usersRouter);
app.use('/api', systemRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  if (err.name === 'UnauthorizedError') {
    res.status(401).send('token 过期')
    return
  }
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
  return
});

module.exports = app;